from rest_framework.response import Response
from rest_framework.views import APIView
from random import randint
from django_redis import get_redis_connection
from meiduo_backend.libs.yuntongxun.sms import CCP
from rest_framework import status
import logging
from meiduo_backend.settings import configurations
from celery_tasks.sms.tasks import send_sms_code
loger = logging.getLogger('django')


class SMSCodeView(APIView):
    """
    get
        发送验证码
    """
    def get(self, request, mobile):
        # 创建redis连接对象
        redis_conn = get_redis_connection('default')

        send_flag = redis_conn.get('is_sendsms_%s' % mobile)
        if send_flag:
            return Response({'message': '请勿频繁发送验证码！'}, status=status.HTTP_400_BAD_REQUEST)
        # 生成验证码
        sms_code = '%06d' % randint(0, 999999)
        loger.info('mobile: %s, sms_code: %s', mobile, sms_code)

        # 创建redis管道(减少连接redis的次数)
        pl = redis_conn.pipeline()
        pl.setex('sms_%s' % mobile, configurations.SMS_CODE_REDIS_EXPIRES, sms_code)
        # 标记验证码发送间隔时间
        pl.setex('is_sendsms_%s' % mobile, configurations.SEND_SMS_CODE_INTERVAL, 1)
        # 执行管道中的命令
        pl.execute()
        # 发短信
        # CCP().send_template_sms(mobile, [sms_code, configurations.SMS_CODE_REDIS_EXPIRES // 60], 1)

        # 触发celery异步任务
        send_sms_code.delay(mobile, sms_code)
        return Response({'message': 'success'})